package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.bean.Dynamic;
import com.sk.bilibili.event.BiliBiliEvent;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import com.sk.bilibili.bean.Forward;
import com.sk.bilibili.mapper.ForwardMapper;

/**
* @author 邵康
* @date 2021/11/24 19:32
*/
@Service
public class ForwardService extends ServiceImpl<ForwardMapper,Forward> {

    @Autowired
    private WarpUtils warpUtils;
    @Autowired
    private MemberService memberService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private TransformUtils transformUtils;
    @Autowired
    private PraiseService praiseService;
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public R<Void> add(Forward forward) {
        forward=transformUtils.transform(forward);
        int memberId = BSessionUtils.getMemberId();
        forward.setMemberId(memberId);
        if(forward.getType()==5){//若对方是转发对象 会直接指向原对象 而不是转发嵌套转发
            Forward temp = getById(forward.getTargetId());
            forward.setType(temp.getType());
            forward.setTargetId(temp.getTargetId());
        }
        save(forward);
        eventPublisher.publishEvent(new BiliBiliEvent<>(this,forward));
        return R.success();
    }

    public R<Void> delete(Integer id) {
        removeById(id);
        return R.success();
    }

    public R<Void> update(Forward forward) {
        updateById(forward);
        return R.success();
    }

    public R<IPage<Forward>> page(Integer page, Integer size) {
        return R.success(page(new Page<>(page,size),null));
    }

    public Forward getWarpForward(Integer id) {
        Forward forward = getById(id);
        forward.getExtra().addExtra(memberService.getById(forward.getMemberId()));
        forward.getExtra().addExtra(warpUtils.getTypeTarget(forward.getType(),forward.getTargetId()));
        int memberId = BSessionUtils.getMemberId();
        forward.getExtra().put("praise",praiseService.hasPraise(memberId,5,id));
        return forward;
    }

    public void changeNum(String field, Integer num, Integer id) {
        redisUtils.changeNum("Forward-"+id,field,num);
    }

    @EventListener(condition = "event.type == 'com.sk.bilibili.service.DynamicService.delete'")
    public void handleDynamicDelete(BiliBiliEvent<Dynamic> event){
        Dynamic dynamic = event.getData();
        if(dynamic.getType()!=5)return;
        delete(dynamic.getTargetId());
    }

}
